<template>
  <k-form-modal
    ref="formRef"
    drawer
    width="649px"
    title="修改会员信息"
    label-width="100px"
    v-bind="formModalState"
    :confirm-disabled="!hasAuth(AuthCode.KGJ_USER_EDIT, false)"
    v-on="formModalEvent"
  >
    <el-form-item label="昵称" prop="nick_name">
      <el-input v-model="state.model.nick_name" disabled placeholder="请输入用户昵称" />
    </el-form-item>
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="state.model.mobile" disabled placeholder="请输入手机号" />
    </el-form-item>
    <el-form-item label="白名单" prop="is_bitwise">
      <el-switch v-model="state.model.is_bitwise" />
    </el-form-item>
    <el-form-item label="价格白名单" prop="price_is_bitwise">
      <el-switch v-model="state.model.price_is_bitwise" />
    </el-form-item>

    <el-form-item label="会员类型" prop="level">
      <el-radio-group v-model="state.model.level" @change="handleLevelChange">
        <el-radio v-for="item in levelOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="到期时间" prop="end_time" :rules="[{ required: true, message: '请选择到期时间' }]">
      <el-date-picker v-model="state.model.end_time" style="width: 100%" type="date" :shortcuts="dateShortcuts" placeholder="请选择到期时间" />
    </el-form-item>
    <el-form-item label="">
      <div class="quick-box">
        <div v-for="item in quickDateMap" :key="item.value" class="item" @click="handleClickQuickDateItem(item)">{{ item.label }}</div>
      </div>
    </el-form-item>
    <el-form-item label="团队人数" prop="slave_count">
      <el-radio-group v-model="state.model.slave_count" :disabled="state.model.level < 20">
        <el-radio v-for="item in newGroupMemberCountOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="封号" prop="is_frozen">
      <el-switch v-model="state.model.is_frozen" @change="(val) => updateRemarkByType(val ? '封号' : '', 2)" />
    </el-form-item>
    <el-form-item label="注销" prop="is_abandon">
      <el-switch v-model="state.model.is_abandon" :disabled="!hasAuthIsAbandon" @change="(val) => updateRemarkByType(val ? '注销' : '', 3)" />
    </el-form-item>
    <el-form-item label="备注" prop="remark" :rules="[{ required: true, message: '请输入备注' }]">
      <el-input v-model="state.model.remark" placeholder="请输入备注" type="textarea" :rows="4" @change="resetRemarkState" />
    </el-form-item>
    <el-form-item label="">
      <div class="quick-box">
        <span v-for="item in wordList" :key="item" class="item" @click="updateRemarkByType(item, 4)">{{ item }}</span>
      </div>
    </el-form-item>
  </k-form-modal>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useFormModal } from '@crud/index';
import { updateUserDetail } from '@/api/crm-kgj/user';
import { levelOptions, wordList, quickDateMap } from '../hooks/use-table';
import { SupremeTeamCountOptions, OtherTeamCountOptions } from '@/constants';
import { hasAuth, AuthCode } from '@/modules/auth';
import { useUpdateRemark } from '@/hooks/use-update-remark';
import { toolGetSingleDateShortCuts as dateShortcuts } from '@/utils';
import dayjs from 'dayjs';
defineOptions({ name: 'MajorCustomerEditModal' });

const formRef = ref();
const emits = defineEmits(['after-submit']);
const cachedData = ref();
const newGroupMemberCountOptions = computed(() => (state.model.level <= 20 ? OtherTeamCountOptions : SupremeTeamCountOptions));
// 是否有修改‘注销’字段权限
const hasAuthIsAbandon = computed(() => hasAuth(AuthCode.KGJ_USER_EDIT_IS_ABANDON, false));

const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  formRef,
  model: {
    remark: '',
    product_type: 1,
    level: 20,
    month: 1,
    slave_count: 1
  },
  getParams: (model) => model,
  onShow: (mode = 0, data: any) => {
    state.model = { ...data, end_time: data.end_time * 1000, remark: data.remark ?? '' };
    cachedData.value = data;
    resetRemarkState();
  },
  onSubmit: async (model, mode = 0) => {
    const { user_id, slave_count, is_frozen, is_bitwise, price_is_bitwise, level: user_level, end_time, remark, is_abandon } = model;
    const params = {
      user_id,
      end_time: dayjs(end_time).unix(),
      slave_count,
      is_frozen,
      is_bitwise,
      price_is_bitwise,
      remark,
      user_level,
      is_abandon
    };
    const res = await updateUserDetail(params);
    if (!res.err) {
      ElMessage.success('保存成功');
      emits('after-submit');
    }
    return res;
  }
});

/** 当会员类型改变时触发
 * 非旗舰版，团队人数重置为1人，且不能选择
 * 旗舰版不受影响
 */
const handleLevelChange = () => {
  if (state.model.level < 20) {
    state.model.slave_count = 1;
  }
};
/** 点击快速快速选择日期的选项的时候触发 */
const handleClickQuickDateItem = (item) => {
  const { value } = item;
  const [val, unit] = value;
  const cachedEndtime = cachedData.value.end_time;

  const currentDate = dayjs().startOf('d').unix().valueOf();
  /** 如果到期时间已经是过期（小于今天0点，则是按过期处理），日期按当天处理（传undefined） */
  const validDate = cachedEndtime < currentDate ? undefined : cachedEndtime * 1000;
  const newDate = dayjs(validDate).add(val, unit).valueOf();
  state.model.end_time = newDate;
  updateRemarkByType(item.label, 1);
};

const { getUpdateRemarkByType, resetRemarkState } = useUpdateRemark();
const updateRemarkByType = (remark: string, type: number) => {
  state.model.remark = getUpdateRemarkByType(state.model.remark, remark, type);
};

defineExpose({
  show: methods.show
});
</script>
<style lang="scss" scoped>
.quick-box {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;

  .item {
    box-sizing: border-box;
    display: flex;
    gap: 4px;
    align-items: center;
    justify-content: center;
    min-width: 50px;
    height: 26px;
    padding: 0 12px;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: border-color .3s ease;

    &:hover {
      border-color: #f1f1f1;
    }
  }
}
</style>
